package com.lemt.user.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemt.common.result.Res;
import com.lemt.common.utils.JwtUtil;
import com.lemt.user.entity.*;
import com.lemt.user.entity.dto.UserLoginDto;
import com.lemt.user.entity.vo.UserInfoVo;
import com.lemt.user.entity.vo.UserRegisterVo;
import com.lemt.user.mapper.*;
import com.lemt.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.digester.Digester;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zik
 * @since 2023-09-10
 */
@Slf4j
@Service(value = "IUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource()
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMeauMapper roleMeauMapper;

    @Resource
    private MeauMapper meauMapper;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;




    @Override
    public String register(UserRegisterVo userRegisterVo) {

        log.info("待判定=》{}",userRegisterVo );
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User :: getPhone ,userRegisterVo.getPhone());
        // 查看数据库是否已存在该手机号
        User getOne = userMapper.selectOne(queryWrapper);
        if (getOne != null){
            return "该手机号已注册";
        }
        User user = new User();
        //将B对象的属性值拷贝到A对象相同字段上
        copyProperties(userRegisterVo,user);
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        log.info("user=>{}",user);
        if (userMapper.insert(user) != 1){
            return "新增用户失败";
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,user.getPhone());
        User getNew = userMapper.selectOne(queryWrapper);
        if (getNew == null){
            return "系统错误";
        }
        // 这个地方应该用批量插入，但是没有找到方法
        List<Role> roles = userRegisterVo.getRoles();
        for (Role  role : roles){
            userRoleMapper.insert(new UserRole(role.getId(),user.getId()));
        }

        return "注册成功";
    }

    @Override
    public String login(UserLoginDto userLoginDto) {
        log.info("接收到user ==>{}",userLoginDto);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,userLoginDto.getUsername()).eq(User::getPhone,userLoginDto.getPhone());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            System.out.println("用户已注册");
            return null;
        }
        String md5Hex1 = DigestUtil.md5Hex( userLoginDto.getPassword());

        System.out.println(md5Hex1);
        if (!user.getPassword().equals(md5Hex1)){
            System.out.println("密码错误");
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("username",user.getUsername());
        map.put("password",user.getPassword());
        map.put("phone",user.getPhone());
        String jwt = JwtUtil.jwt(map);
        System.out.println("token密文："+jwt);

        // redis储存token 及 user
        redisTemplate.opsForValue().set("lemt:login:token:"+user.getPhone(),jwt,30, TimeUnit.MINUTES);

        System.out.println("放入成功");


        return jwt;
    }

    @Override
    public UserInfoVo getUserInfo(Integer id) {

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, id));
        if (user == null){
            return null;
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        copyProperties(user,userInfoVo);
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        if (userRoles == null){
            return userInfoVo;
        }

        List<Role> roles = new ArrayList<>();
        for (UserRole userRole:userRoles){
            roles.add(roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getId, userRole.getRoleId())));
        }
        userInfoVo.setRoles(roles);
        log.info("roles=> {}",roles);
        Set<Integer> meaus = new HashSet<>();
        for (Role role :roles){
            List<RoleMeau> roleMeaus = roleMeauMapper.selectList(new LambdaQueryWrapper<RoleMeau>().eq(RoleMeau::getRoleId, role.getId()));

            log.info(" roleMeaus =》{}",roleMeaus);
            for (RoleMeau roleMeau:roleMeaus){
                log.info("roleMeau =》 {}",roleMeau);
                meaus.add(roleMeau.getMeauId());
            }
        }
        if (meaus.isEmpty()){
            return userInfoVo;
        }
        System.out.println("获取权限");
        List<Meau> meaus1 = meauMapper.selectBatchIds(meaus);
        if (meaus1 == null){
            return userInfoVo;
        }
        userInfoVo.setMeaus(meaus1);
        return userInfoVo;
    }
}
